import { TabbarPageEnum } from '@/enums/pageEnum';
import { SceneValuesEnum } from '@/enums/sceneValuesEnum';
import { getUrlName, navigateTo } from '@/router';
import type { Pages } from '@/router/types/pages';
import { useUserStoreWithOut } from '@/store/modules/user';

const toString = Object.prototype.toString;

export function is(val: unknown, type: string) {
  return toString.call(val) === `[object ${type}]`;
}

export function isIos(system?: string): boolean {
  if (!system) system = uni.getDeviceInfo().system;
  return system.toLowerCase().includes('ios');
}

export function isNewIphone(model?: string): boolean {
  if (!model) model = uni.getDeviceInfo()?.model || uni.getSystemInfoSync()?.model;
  // model = model.replace(' ', '').toLowerCase();
  model = model.toLowerCase();
  return model.includes('iphone X') || model.includes('iphone x') || model.includes('iphone 1');
}

export function isDef(val?: any) {
  return typeof val !== 'undefined';
}

export function isUnDef(val?: any) {
  return !isDef(val);
}

export function isObject(val: any): val is Record<any, any> {
  return val !== null && is(val, 'Object');
}

export function isEmpty(val: any) {
  if (isArray(val) || isString(val)) {
    return val.length === 0;
  }

  if (val instanceof Map || val instanceof Set) {
    return val.size === 0;
  }

  if (isObject(val)) {
    return Object.keys(val).length === 0;
  }

  return false;
}

export function isDate(val: unknown): val is Date {
  return is(val, 'Date');
}

export function isNull(val: unknown): val is null {
  return val === null;
}

export function isNullOrUnDef(val: unknown): val is null | undefined {
  return isUnDef(val) || isNull(val);
}

export function isNumber(val: any): val is number {
  return /^[+-]?\d+(\.\d+)?$/.test(val)
}

export function isPromise<T = any>(val: unknown): val is Promise<T> {
  return is(val, 'Promise') && isObject(val) && isFunction(val.then) && isFunction(val.catch);
}

export function isString(val: unknown): val is string {
  return is(val, 'String');
}

export function isFunction(val: unknown): val is Function {
  return typeof val === 'function';
}

export function isBoolean(val: unknown): val is boolean {
  return is(val, 'Boolean');
}

export function isRegExp(val: unknown): val is RegExp {
  return is(val, 'RegExp');
}

export function isArray(val: any): val is Array<any> {
  return val && Array.isArray(val);
}

export function isWindow(val: any): val is Window {
  return typeof window !== 'undefined' && is(val, 'Window');
}

export function isElement(val: unknown): val is Element {
  return isObject(val) && !!val.tagName;
}

export function isMap(val: unknown): val is Map<any, any> {
  return is(val, 'Map');
}

/** 是否包含中文 */
export function isIncludeChinese(str: string) {
  return /.*[\u4e00-\u9fa5]+.*$/.test(str);
}

/** 是否为数组字符串 */
export function isArrayString(str: string) {
  return str && str[0] === '[' && str[str.length - 1] === ']';
}

export function isJSON(jsonStr: string) {
  if (typeof jsonStr == 'string') {
    try {
      var obj = JSON.parse(jsonStr);
      if (typeof obj == 'object' && obj) {
        return obj;
      } else {
        return false;
      }
    } catch (e) {
      // console.log('error：' + jsonStr + '!!!' + e);
      return false;
    }
  }
}

export const isServer = typeof window === 'undefined';

export const isClient = !isServer;

export function isReqUrl(path: string): boolean {
  const reg = /(http|https):\/\/([\w.]+\/?)\S*/;
  return reg.test(path);
}

/**
 * 判断是否已登录
 * @export
 * @param {Function} [fn]
 * @param {Boolean} isBackHome 登录页左上角是否返回到home
 * @description ( 需要登录的页面, 跳转登录页, 却未登录时返回home )
 * @return {*}
 */
export async function isLogin(
  fn: () => void,
  isBackHome?: boolean
): Promise<any> {
  const { scene } = uni.getEnterOptionsSync()
  /** 朋友圈单页模式时, 触发系统提示 */
  if (scene === SceneValuesEnum.TIMELINE_SINGLEPAGE) return uni.navigateBack()
  const { token, userInfo, login } = useUserStoreWithOut();
  if (!token) await login()
  if (!userInfo.phonenumber) {
    navigateTo({ name: 'loginPhone', options: { isBackHome, success: fn } })
  } else {
    fn?.()
  }
}
/**
 * 判断分享是否为右上角菜单触发
 * @export
 * @param {('button' | 'menu' | string)} from
 * @return {*}
 */
export function isShareMenu(from: 'button' | 'menu' | string): boolean {
  return from === 'menu';
}

/**
 * 当前是否在管理员分包中
 * @returns {boolean}
 */
export function isAdminSubpackage(): boolean {
  const pages = getCurrentPages();
  const adminPage = pages.find((v) => v.route && v.route.includes('pages/admin'));
  return !!adminPage;
}

/**
 * @description 判断是否为自定义tabbar页面
 * @date 18/10/2024
 * @export
 * @param {string} path
 */
export function isDynamicPathTabbarPage(path: string) {
  const pathName = urlConvertToName(path);
  return (
    // pathName === TabbarPageEnum.BASE_HOME ||
    // pathName === TabbarPageEnum.BASE_MINE ||
    pathName === 'puppetTaabarPage_1' ||
    pathName === 'puppetTaabarPage_2' ||
    pathName === 'puppetTaabarPage_3'
  );
}

/**
 * @description 获取url中的页面名称
 * @date 18/10/2024
 * @export
 * @param {string} path
 */
export function urlConvertToName(path: string) {
  return (path?.includes('pages') ? getUrlName(path) : path) as keyof typeof Pages;
}
